﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using wsn.ap;
using wsn.atos;
using System.Threading;
using wsn.svc;

namespace wsn
{
    public class Service
    {
        Thread recvThread;
        Thread dealThread;
        IAccessPoint accessPoint;
        private static List<AccessPointData> buf = new List<AccessPointData>();

        public Service()
        {
            recvThread = new Thread(recvThreadRun);
            recvThread.Name = "recvThread";
            dealThread = new Thread(dealThreadRun);
            dealThread.Name = "dealThread";
        }

        public static void addPointData(AccessPointData data)
        {
            lock (buf)
            {
                buf.Add(data);
            }
        }

        public void open()
        {
            //从数据库中加载数据
            Daofactory.loadData();
            //打开接入点
            accessPoint = new ComAccessPoint();
            accessPoint.setConponent(new AtosComponent());
            if (accessPoint.Open() == false)
            {
                Console.WriteLine("接入点打开失败");
                return;
            }
            //接收数据
            recvThread.Start(accessPoint);
            //处理数据
            IDataService dataService = new DataService();
            dealThread.Start(dataService);

        }
        public void close()
        {
            //停止接收数据
            if (recvThread.IsAlive)
                recvThread.Abort();
            //停止处理数据
            if (dealThread.IsAlive)
                dealThread.Abort();
            //关闭接入点
             accessPoint.Close();
            //保存数据
             Daofactory.storeData();
        }
        private void recvThreadRun(Object o)
        {
            IAccessPoint ap = (IAccessPoint)o;
            ap.run();
        }

        private void dealThreadRun(Object o)
        {
            IDataService svc= (IDataService)o;
            AccessPointData data;
            while (true)
            {
                lock (buf)
                {
                    if (buf.Count > 0)
                    {
                        data = buf.First();
                        buf.Remove(data);
                    }
                    else
                        data=null;
                }
                if (data == null)
                {
                    Thread.Sleep(1000);
                    continue;
                }
                svc.setData(data);
                svc.execute();
            }
            
        }

    }
}
